import 'package:flutter/material.dart';
import 'package:flutter_verification_box/verification_box.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:xlsk/api/model/login.dart';
import 'package:xlsk/routes/xlsk_router.dart';
import 'package:xlsk/utils/dimension.dart';
import 'dart:async';

class Code extends StatefulWidget {
  var phone;
  Code({this.phone});

  @override
  State<StatefulWidget> createState() {
    return _codeState();
  }
}

class _codeState extends State<Code> {
  bool coding = false; // 是否正在获取code
  int countDown = 60; //倒计时
  var myTimer = null;

  @override
  void initState() {
    super.initState();
    start(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: GestureDetector(
          child: Icon(Icons.arrow_back_ios,color: Color.fromRGBO(31, 35, 41, 1),size: 24,),
          onTap: (){
            XlskRouter.back(context);
          },
        ),
        title: Text(""),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              child: Text('输入短信验证码',style: TextStyle(color: Color(0xFF1F2329),fontSize: Dimension(context).toPx(24),fontWeight: FontWeight.w700)),
              margin: EdgeInsets.only(top: Dimension(context).toPx(64)),
            ),
            Container(
              child: Row(
                children: [
                  Text('验证码已发送至',style: TextStyle(color: Color(0xFF8F959E),fontSize: Dimension(context).toPx(14))),
                  Container(
                    child: Text('+86 ${widget.phone}',style: TextStyle(color: Color(0xFF1F2329),fontSize: Dimension(context).toPx(16))),
                    margin: EdgeInsets.only(left: Dimension(context).toPx(8)),
                  )
                ],
              ),
              margin: EdgeInsets.only(top: Dimension(context).toPx(10)),
            ),
            Container(
              child: VerificationBox(
                type: VerificationBoxItemType.underline,
                showCursor: true,
                borderWidth:2,
                cursorWidth: 2,
                cursorColor: Color(0xFF1661FF),
                cursorIndent: 10,
                cursorEndIndent: 10,
                textStyle: TextStyle(color: Color(0xFF1F2329),fontSize: Dimension(context).toPx(30),fontWeight: FontWeight.w700),
                focusBorderColor: Color(0xFF1661FF),
                unfocus: false,
                onSubmitted: (value){
                  submitCode(context,value);
                },
              ),
              height: Dimension(context).toPx(40),
              margin: EdgeInsets.only(top: Dimension(context).toPx(58)),
            ),
            Container(
              child: GestureDetector(
                child: coding?Text(countDown<60?'${countDown}秒后重新发送':'发送中...',style: TextStyle(color: Color(0xFF646A73),fontSize: Dimension(context).toPx(14))):Text('重新发送',style: TextStyle(color: Color(0xFF1661FF),fontSize: Dimension(context).toPx(14))),
                onTap: (){
                  this.start(context);
                },
              ),
              margin: EdgeInsets.only(top: Dimension(context).toPx(40)),
            )
          ],
        ),
        padding: EdgeInsets.symmetric(horizontal: Dimension(context).toPx(32)),
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        constraints: BoxConstraints(
          minWidth: Dimension(context).toVw(100),
          minHeight: Dimension(context).toVh(100)
        ),
      ),
    );
  }

  void submitCode(context,code){ // 提交验证码
    Map<String,dynamic> data = {
      "mobile": widget.phone,
      "verifycode":code
    };
    Login().submitCode(context, '/Login/xcxplogin', data);
  }
  
  void start(context) async{ // 开始倒计时
    if(this.coding){ //如果正在获取倒计时，显示提示信息
      EasyLoading.showToast('请稍后再发送验证码');
    }else{
      setState(() {
        coding = true;
      });
      Map<String,dynamic> data = {
        'mobile': widget.phone
      };
      var res = await Login().sendCode(context, '/Login/sendverifycode', data);
      if(res['code'] == 100){
        setState(() {
          coding = false;
        });
      }else{
        setState(() {
          countDown = 59;
        });
        // 发送验证码请求
        var mytimer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
          if(this.countDown <= 1){
            timer.cancel();
            setState(() {
              coding = false;
            });
          }
          setState(() {
            countDown--;
          });
        });
        setState(() {
          myTimer = mytimer;
        });
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    if(myTimer != null){
      myTimer.cancel();
    }
  }
}
